from typing import Any, Dict, Optional
from config import logger
from llm_client import LLMClient


class QueryParser:
    def parse_natural_language(query: str) -> Optional[Dict[str, Any]]:
        try:  # query 查询分数大于等于60分的女同学的信息，按分数从高到底排序，只返回前3条
            prompt = f"""
            请分析以下中文查询，识别查询意图、涉及的表、条件、操作类型
            查询内容:{query} 
            请以JSON格式返回结果，包含以下的字段:
            - operation：操作类型(SELECT/INSERT/UPDATE/DELETE)
            - tables:涉及的表名列表(students/subjects/scores)
            - conditions： 查询条件列表，每个条件包含(字段，操作符，值)
            - limit: 返回记录上限(可选)
            - order_by: 排序字段(可选)

            示例输出:
            {{
                "operation": "SELECT",
                "tables": ["students","scores"],
                "conditions": [["gender","=","男"],["score",">=","80"]],
                "limit": 10,
                "order_by": "score DESC",
            }}
            """
            parsed_result = LLMClient.call_llm_json(prompt)
            if parsed_result is None:
                logger.warning(f"LLM返回格式无效，使用默认解析")
                return {
                    "operation": "SELECT",
                    "tables": ["students"],
                    "conditions": [],
                    "limit": None,
                    "order_by": None,
                    "original_query": query,
                }
            else:
                return {
                    "operation": parsed_result.get("operation", "SELECT"),
                    "tables": parsed_result.get("tables", ["students"]),
                    "conditions": parsed_result.get("conditions", []),
                    "limit": parsed_result.get("limit"),
                    "order_by": parsed_result.get("order_by"),
                    "original_query": query,
                }

        except Exception as e:
            logger.warning(f"LLM解析失败，使用默认解析:{str(e)}")
            return {
                "operation": "SELECT",
                "tables": ["students"],
                "conditions": [],
                "limit": None,
                "order_by": None,
                "original_query": query,
            }
